//app.js
var Ajax = require('./utils/Ajax.js');
var utils = require('./utils/util.js');
var config = require('./base.conf.js').config;
var wxDecodeObj = require("./utils/wxDecode.js");
// const ald = require('./utils/ald-stat.js');//阿拉丁统计
var k = 0;
App({
  onLaunch: function() {
    var that = this
    wx.getSystemInfo({ //  获取页面的有关信息
      success: (res) => {
        this.globalData.model = res.model.indexOf('iPhone X') > -1 ? true : '';
        this.globalData.navigationBarHeight = res.statusBarHeight + 44;
        var ww = res.windowWidth;
        var hh = res.windowHeight;
        this.globalData.ww = ww;
        this.globalData.hh = hh;
      }
    })
  },
  onShow(e) {
    this.globalData.channelInfo = e.query;
    this.globalData.scene = e.scene;
    this.globalData.weChatInfo = utils.getWechatInfo();
    this.globalData.userInfo = utils.getUserInfo();
    this.globalData.getUserStep = utils.getUserStep();
    this.globalData.islogin = utils.getUserInfo() ? true : false;
    if (!utils.getUserStep()) {
      this.WxLoginInit(true);
    }
  },
  getApi(_api) {
    return Ajax.getApi(_api);
  },
  WxLoginInit: function(isll = false, callBack) { //自动登录只能获取到sessionKey与openid
    this.wxLogin((state, msg, data) => { //根据微信自带API获取到code
      if (state) {
        var url = isll ? 'onLogin' : "toLogin"; //接口不统一暂时用
        Ajax.get("toLogin", {
          code: data
        }).then((d) => {
          if (d.status == 200) {
            this.saveSync("sessionKey", d.data.session_key);
            this.saveSync("openid", d.data.openid);
            if (callBack) {
              callBack(true, "授权成功", d.data);
            }
          } else {
            if (callBack) {
              callBack(false, "授权失败", null);
            }
          }
        }).catch((e) => {
          console.log(e)
          utils.showtoast("请求数据失败,请检查网络")
          if (callBack) {
            callBack(false, "请求数据失败", null);
          }
        })
      } else {
        return state;
      }
    })
  },
  autoLoginNew: function(data, callBack) { //根据open-type="getUserInfo" 解码用户信息根据解码用户信息中的unionId获取用户信息
    if (utils.getUserInfo() == null) { //是否已经登录
      utils.showLoading();
      //data是open-type="getUserInfo"回掉函数返回的数据（用户信息已及加密用户信息）
      this.newWxLogin(data, (state, rData) => { //解密用户信息返回解密后用户信息根据unionId获取获取用户信息
        if (state) { //解密成功获取用户信息
          rData && rData.data.decodeData.unionId && this.saveSync("unionId", rData.data.decodeData.unionId); //判断信息是否完整。并保存unionId；
          this.updataStep((status, rdata) => {
            console.log(status, rdata)
          }, null, false)
          if (callBack) {
            callBack(true, "已自动登录");
          }
        } else {
          if (callBack) {
            callBack(false, "获取授权失败")
          }
        }
      })
    } else {
      console.log('已自动登录')
    }
  },
  newWxLogin: function(data, callBack) { //根据所传参数('授权成功d的个人信息')解码unionId
    utils.showLoading();
    var decodeData = null;
    var sessionKey = this.getValueSync("sessionKey");
    if (!sessionKey) { //没有sessionKey用微信code轮循获取直到获取成功
      this.WxLoginInit(true, (state, msg) => {
        if (state) { //成功获取到code
          this.newWxLogin(data, callBack);
          console.log(state)
        } else {
          utils.showtoast(msg)
        }
      })
      utils.hideLoading();
      return;
    }
    try { //解码unionId
      var decodeObj = new wxDecodeObj(this.globalData.appId, sessionKey);
      decodeData = decodeObj.decryptData(data.encryptedData, data.iv);

    } catch (e) {
      console.log(e)
      if (callBack) {
        callBack(false, { //解码失败，返回错误信息
          msg: "fail",
          data: "获取用户信息失败"
        })
      }
      utils.hideLoading();
      return;
    }
    utils.hideLoading();
    if (callBack) {
      var data = {
        "userInfo": data.userInfo,
        "decodeData": decodeData
      };
      this.save("weChatInfo", JSON.stringify(data));
      this.save("unionId", data.decodeData.unionId);
      this.globalData.unionId = data.decodeData.unionId
      callBack(true, { //
        msg: "ok", //解码成功
        data: data //返回用户信息
      })
    }
  },
  wxLogin: function(callBack) { //微信自带登录获取code
    wx.login({
      success: (res) => {
        if (callBack) {
          if (res.code) {
            callBack(true, res.errMsg, res.code) //成功的回调返回 获取的状态，提示，code
          } else {
            callBack(false, res.errMsg)
          }
        }
      },
      fail: () => {
        if (callBack) {
          callBack(false, "授权失败")
        }
      }
    })
  },
  getWeRun(callBack, isupdata = false, mandatory = false) { //首次拉起授权
    wx.getWeRunData({
      success: (res) => {
        // this.WxLoginInit(true, (state, msg) => {
        //   if (state) { //成功获取到code
        var sessionKey = this.getValueSync("sessionKey");
        var decodeData = null;
        try { //解码unionId
          var decodeObj = new wxDecodeObj(this.globalData.appId, sessionKey);
          decodeData = decodeObj.decryptData(res.encryptedData, res.iv);
        } catch (e) {
          k++;
          if (k > 5) {
            k = 0;
            if (callBack) {
              callBack(false, { //解码失败，返回错误信息
                msg: "fail",
                data: "获取用户步数失败"
              })
            }
            utils.hideLoading();
          } else {
            this.WxLoginInit(true, (state, msg) => {
              if (state) { //成功获取到code
                this.getWeRun(callBack, isupdata, mandatory);
              } else {
                if (callBack) {
                  callBack(false, { //解码失败，返回错误信息
                    msg: "fail",
                    data: "获取用户步数失败"
                  })
                }
                utils.hideLoading();
              }
            })
          }
          return;
        }
        this.updataStep(callBack, decodeData, isupdata);

      },
      fail: (e) => {
        console.log(e)
        if ((e.errMsg).indexOf("fail cancel") > -1 || (e.errMsg).indexOf("微信运动") > -1) {
          callBack && callBack(false, { //解码失败，返回错误信息
            msg: "fail",
            data: "微信运动未授权"
          })
        } else {
          wx.showModal({
            title: '邻里邻外',
            content: '请授权我们获取您的微信运动步数。',
            complete: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    console.log(res)
                    if (res.authSetting['scope.werun']) {
                      this.getWeRun(callBack, isupdata, mandatory);
                    } else {
                      mandatory && this.getWeRun(callBack, isupdata, mandatory);
                    }
                  },
                  fail: (e) => {
                    console.log(e)
                    mandatory && this.getWeRun(callBack, isupdata, mandatory);
                  }
                })
              } else {
                mandatory && this.getWeRun(callBack, isupdata, mandatory);
              }
            }
          })
        }
        utils.hideLoading();
      }
    })

  },
  updataStep(callBack, decodeData, isupdata) { //callBack 回调函数, decodeData步数的数据信息, isupdata是否初始化或者更新信息
    var unionId = this.getValueSync("unionId");
    var ChatInfo = utils.getWechatInfo();
    var {
      getUserStep
    } = this.globalData;
    if (unionId && ChatInfo) {
      var getUrl = 'initStep';
      var objdata = {
        unionId: unionId,
        wxName: ChatInfo.userInfo && ChatInfo.userInfo.nickName || '',
        wxPortrait: ChatInfo.userInfo && ChatInfo.userInfo.avatarUrl || ''
      }
      if (decodeData) { //授权初始化
        objdata.wxStep = decodeData && decodeData.stepInfoList[decodeData.stepInfoList.length - 1].step
      }
      if (isupdata) {
        getUrl = 'updateSysStep';
        objdata = {
          uuid: getUserStep.uuid,
          wxStep: (decodeData && decodeData.stepInfoList[decodeData.stepInfoList.length - 1].step) || 0,
        }
      }
      Ajax.post(getUrl, objdata).then((d) => {
        if (d.status == 200 && d.data) {
          d.data.sysStep = d.data.sysStep < 0 ? 0 : d.data.sysStep;
          this.save("sysStep", JSON.stringify(d.data));
          this.globalData.getUserStep = d.data;
          if (callBack) {
            callBack(true, { //
              msg: "ok", //解码成功
              data: d.data,
            })
          }
        } else {
          d.msg != '该用户不存在或未授权' && utils.showtoast(d.msg || d.message || d.data || '服务器错误')
          if (callBack) {
            callBack(false, { //解码失败，返回错误信息
              msg: "fail",
              data: "获取用户步数失败",
              ststus: d.msg || ''
            })
          }
        }
      }).catch((e) => {
        console.log(e)
        utils.showtoast('网络错误,请检查您的网络')
        if (callBack) {
          callBack(false, { //解码失败，返回错误信息
            msg: "fail",
            data: "获取用户步数失败"
          })
        }
      })
    }
  },
  save: function(key, value) { //保存信息到Storage 传入key ，value
    wx.setStorage({
      key: key,
      data: value,
    })
  },
  saveSync: function(key, value) {
    wx.setStorageSync(key, value);
  },
  getValueSync: function(key) {
    return wx.getStorageSync(key);
  },
  //发送formid到后台
  sendFormid: function(formid) {
    if (formid == "the formId is a mock one") return
    var data = {
      formId: formid,
      openId: this.getValueSync("openid"),
      unionId: this.getValueSync("unionId"),
      appId: this.globalData.appId,
      expireTime: new Date().getTime() + 604800000, //计算7天后的过期时间时间戳,
    }
    Ajax.post('addXcxFromId', data).then((d) => {
      console.log(d)
      if (d.status == 200 && d.data) {
        console.log(d)
      } else {
        console.log(d)
      }
    }).catch((e) => {
      console.log(e)
    })
  },
  globalData: {
    model: '',
    navigationBarHeight: 0,
    userInfo: null,
    islogin: '',
    appId: "wxbdde3b565bec2a9f",
    channelInfo: {},
    getUserStep: null,
    openId: "",
    referrerInfo: {},
    scene: -1,
    weChatInfo: null,
    isgetUid: false,
    pageSource: "plsc",
    unionId: '',
  }
})